import random

import time
from concurrent.futures import ThreadPoolExecutor, Future

pool = ThreadPoolExecutor(10)
# pool.submit(函数名,参数1,参数2,...)

url_list = ["www.xxx-{}.com".format(i) for i in range(200)]


def task(video_url, num):
    print("开始任务", video_url)
    time.sleep(3)
    print("结束任务:", video_url) # 别放return 之后
    return num*random.randint(0, 10)


def test_thread_pool():
    print()
    print("start...")
    for url in url_list:
        pool.submit(task, url, 2)
    print()
    print("end...")


def done(response):
    print("任务执行后的返回值：", response.result())


def test_thread_pool_wait():
    print()
    print("start...")
    for url in url_list:
        pool.submit(task, url, 2)
    print()
    print("running...\n")
    pool.shutdown(True)  # 相当于单线程的shutdown
    print("true end")


def test_thread_pool_hook():
    print()
    print("start...")
    for url in url_list:
        future = pool.submit(task, url, 2)
        future.add_done_callback(done)  # 用于分工;不用破坏之前的代码
    print()
    print("end...")


def test_thread_pool_hook_uni_handle():  # 统一处理
    future_list = []
    print()
    print("start...")
    for url in url_list:
        future = pool.submit(task, url, 2)
        future_list.append(future)
    print()
    print("end...")

    # pool.shutdown(True)
    # total=0
    # for fu in future_list:
    #     print(fu.result())
    #     total += fu.result()
    # print("total_sum:", total)